package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StreamOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT =new DefaultRedisScript<>();
    static{
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private static final ExecutorService SECKILL_ORDER_EXECUTOR= Executors.newSingleThreadExecutor();

    // postConstruct是bean的初始化方法
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private class VoucherOrderHandler implements Runnable{

        @Override
        public void run() {
            while(true){
                try {
                    //1. 获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 count 1 block 2000 streams s1 >
                    List<MapRecord<String, Object, Object>> recordList = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed())
                    );

                    //2. 判断订单信息是否为空
                    if (recordList==null||recordList.isEmpty()) {
                        continue;
                    }

                    //3. 解析数据
                    MapRecord<String, Object, Object> record = recordList.get(0);
                    Map<Object, Object> recordValue = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(recordValue, new VoucherOrder(), true);

                    //4. 创建订单
                    createVoucherOrder(voucherOrder);

                    //5. 确认消息ack
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders","g1",record.getId());
                } catch (Exception e){
                    // 如果失败, 需要处理异常订单
                    log.error("处理订单异常",e);
                    handlePendingList();

                }

            }
        }

        private void handlePendingList() {
            while (true) {
                try {
                    // 1.获取pending-list中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create("stream.orders", ReadOffset.from("0"))
                    );
                    // 2.判断订单信息是否为空
                    if (list == null || list.isEmpty()) {
                        // 如果为null，说明没有异常消息，结束循环
                        break;
                    }
                    // 解析数据
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    // 3.创建订单
                    createVoucherOrder(voucherOrder);
                    // 4.确认消息 XACK
                    stringRedisTemplate.opsForStream().acknowledge("s1", "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                }
            }
        }
    }

    private void createVoucherOrder(VoucherOrder voucherOrder) {
        //1. 尝试获取锁
        Long orderId = voucherOrder.getId();
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();

        RLock lock = redissonClient.getLock("lock:order:" + userId);
        try {
            boolean tryLock = lock.tryLock();
            if(!tryLock){
                //2. 获取锁失败, 则直接返回重试
                log.error("不允许重复下单");
                return;
            }

            // 通常订单流程
            createOrder(voucherId,userId,orderId);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        // 获取用户id
        Long userId = UserHolder.getUser().getId();
        // 获取订单id
        long nextId = redisIdWorker.nextId("order");
        //1. 执行Lua脚本
        Long luaResult = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(),String.valueOf(nextId)
        );

        //2. 判断结果是否为0
        int r = luaResult.intValue();
        if(r !=0){
            //2.1 为0,则返回异常
            return Result.fail(r==1?"库存不足":"不允许重复下单");
        }
        //2.2 不为0,则往下走

        //3. 将优惠券id,用户id和订单id存入阻塞队列


        //考虑使用redis中的stream实现->实际在lua脚本中执行

        //4. 返回id
        return Result.ok(nextId);
    }

    /*@Override
    public Result seckillVoucher(Long voucherId) {
        //1.查询优化全信息
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);

        //2. 判断秒杀优化券是否存在
        if(seckillVoucher==null){
            return Result.fail("秒杀优惠券不存在");
        }

        //3. 如果不在秒杀区间(开始结束时间内),则直接结束
        LocalDateTime beginTime = seckillVoucher.getBeginTime();
        if(beginTime.isAfter(LocalDateTime.now())){
            return Result.fail("秒杀还没有开始");
        }
        LocalDateTime endTime = seckillVoucher.getEndTime();
        if(endTime.isBefore(LocalDateTime.now())){
            return Result.fail("秒杀已经结束");
        }

        //4. 如果在秒杀区间内,则判断库存是否充足
        //5. 库存不足,则返回异常
        if (seckillVoucher.getStock()<1) {
            return Result.fail("优化券已经抢完");
        }

        Long userId = UserHolder.getUser().getId();

//        SimpleRedisLock lock = new SimpleRedisLock(stringRedisTemplate, "order:"+userId);
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean tryLock = lock.tryLock();
        if(!tryLock){
            return Result.fail("请不要重复提交订单");
        }

        // 加上悲观锁,以保证创建订单时单用户被锁住
        // 悲观锁的键,取userId的toString方法后,需要再取intern,以保证每次都获取一样的值
        //synchronized (userId.toString().intern()){
            // 要使事务生效,需要使用代理对象执行方法.
            // 方法之一是从AopContext中获取该对象
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createOrder(voucherId, userId);
        } finally {
            lock.unlock();
        }
        //}
    }*/

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result createOrder(Long voucherId, Long userId) {
        return createOrder(voucherId,userId,redisIdWorker.nextId("order"));
        /*int count = query().eq("voucher_id", voucherId).eq("user_id", userId).count();
        if(count>0){
            return Result.fail("当前用户已经下了订单");
        }

        //6. 库存充足,则扣减库存
        boolean update = seckillVoucherService.update()
                .setSql("stock=stock-1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0)
                .update();
        if (!update) {
            return Result.fail("库存不足");
        }

        //7. 同时创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(redisIdWorker.nextId("order"));
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);

        //8. 结束返回订单id
        return Result.ok(voucherOrder.getId());*/
    }

    @Transactional
    public Result createOrder(Long voucherId,Long userId,Long orderId){
        int count = query().eq("voucher_id", voucherId).eq("user_id", userId).count();
        if(count>0){
            return Result.fail("当前用户已经下了订单");
        }

        //6. 库存充足,则扣减库存
        boolean update = seckillVoucherService.update()
                .setSql("stock=stock-1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0)
                .update();
        if (!update) {
            return Result.fail("库存不足");
        }

        //7. 同时创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        save(voucherOrder);

        //8. 结束返回订单id
        return Result.ok(voucherOrder.getId());
    }
}
